﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Frame.Global;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxGridView.Export;
using System.IO;
using DevExpress.Web.ASPxEditors;
using System.Data.SqlClient;

namespace Frame.Pages
{
    /// <summary>
    /// 可定制型简单查询基类
    /// 注: 本基类使用会使用Session缓存数据，慎用
    /// </summary>
    public abstract class SimpleQueryPage : BasePage
    {
        
        #region 组件(Component)
        protected ASPxGridView gridView;
        /// <summary>
        /// SimpleQueryPage的查询用GridView属性默认为gridView
        /// </summary>
        public virtual ASPxGridView SQueryGridView
        {
            get { return gridView; }
        }
        #endregion

        #region 构造函数  (Constructors)
        public SimpleQueryPage()
            : base()
        {
        }
        #endregion

        #region 公共属性 (Public Perproty)
        /// <summary>
        /// 保存gridView的DataSource的Session的SessionName
        /// </summary>
        protected abstract string SQuerySessionName
        {
            get;
        }
        /// <summary>
        /// 用于不同级别的sql
        /// </summary>
        protected abstract string SQuerySQLString
        {
            get;
        }
        /// <summary>
        /// 主GridView数据源的表名
        /// </summary>
        public abstract string SQueryTableName
        {
            get;
        }

        private SqlParameter[] _SQuerySQLParams;
        /// <summary>
        /// 数据检索参数
        /// </summary>
        public SqlParameter[] SQuerySQLParams
        {
            get { return _SQuerySQLParams; }
            set { _SQuerySQLParams = value; }
        }
        /// <summary>
        /// SQuery页的主DateSet
        /// </summary>
        public uDataSet SQueryDateSet
        {
            get
            {
                if (Session[SQuerySessionName] != null)
                {
                    return Session[SQuerySessionName] as uDataSet;
                }
                else
                {
                    throw new Exception("尚未对SQueryDateSet进行赋值");
                }
            }
            set
            {
                Session[SQuerySessionName] = value;
            }
        }

        bool m_IsUseCacheSession = false;
        /// <summary>
        /// 是否直接使用Session中缓存的数据而不是重新获取数据作为数据源
        /// </summary>
        public bool IsUseCacheSession
        {
            get { return m_IsUseCacheSession; }
            set { m_IsUseCacheSession = value; }
        }
        #endregion

        #region 方法 (Method)
        /// <summary>
        /// Page_Load事件（包含了绑定SQueryGridView数据的方法）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            if (IsUseCacheSession)
            {
                if (!IsPostBack && Session[SQuerySessionName] == null)
                {
                    SQueryDateSet = new uDataSet(SQuerySQLString, SQueryTableName, SQuerySQLParams);
                }
                else
                {
                    SQueryDateSet = Session[SQuerySessionName] as uDataSet;
                }
            }
            else
            {
                if (!IsPostBack)
                {
                    SQueryDateSet = new uDataSet(SQuerySQLString, SQueryTableName, SQuerySQLParams);
                }
                else
                {
                    SQueryDateSet = Session[SQuerySessionName] as uDataSet;
                }
            }
            foreach (GridViewColumn item in gridView.Columns)//通过foreach例遍所有的Columns
            {
                if (item is GridViewDataComboBoxColumn)//当响应的columns为下拉框时设置文字显示为居中
                {
                    item.CellStyle.HorizontalAlign = HorizontalAlign.Center;
                }
            }
            //由于会产生设置visible错误暂时停用
            //SQueryTrimGridColumns(SQueryGridView, dt);
            SQuerySetGridBeforeBind();
            SQueryGridView.DataSource = SQueryDateSet.Tables[SQueryTableName];
            SQueryGridView.DataBind();
        }
        /// <summary>
        /// 在GridView绑定数据之前对其进行设置
        /// </summary>
        protected virtual void SQuerySetGridBeforeBind()
        {
            //throw new Exception("The method or operation is not implemented.");
        }

        /// <summary>
        /// 按获取的DataTable内容设置GridView的列的可见性
        /// </summary>
        /// <param name="gridView">GridView</param>
        /// <param name="dt">用于绑定GridView的DataTable</param>
        protected void SQueryTrimGridColumns(ASPxGridView gGridView, DataTable dt)
        {
            string[] fieldNames = new string[dt.Columns.Count];
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                fieldNames[i] = dt.Columns[i].ColumnName;
            }
            foreach (GridViewColumn gvc in gGridView.Columns)
            {
                if (gvc is GridViewCommandColumn)
                {

                }
                else
                {
                    try
                    {
                        gvc.Visible = IsStringINArray((gvc as GridViewDataColumn).FieldName, fieldNames);
                    }
                    catch
                    {
                        throw new Exception("网格绑定未知错误！请联系管理员");
                    }
                }
            }
        }

        /// <summary>
        /// 按sqlstr获取下拉框列的item
        /// </summary>
        /// <param name="ColumnName">下拉框列的列名</param>
        /// <param name="strsql">获取item的sql</param>
        /// <param name="TextField">下拉框的text列映射值</param>
        /// <param name="ValueField">下拉框的value列映射值</param>
        protected void SQueryPolutateComboBoxColumn(string ColumnName, string strsql, string TextField, string ValueField)
        {
            GridViewDataComboBoxColumn gvdcb = gridView.Columns[ColumnName] as GridViewDataComboBoxColumn;
            DataTable dt = new DataTable();
            dt = GlobalSqlHelper.ExecuteSQLToDataTable(strsql);
            foreach (DataRow dr in dt.Rows)
            {
                gvdcb.PropertiesComboBox.Items.Add(new DevExpress.Web.ASPxEditors.ListEditItem(dr[TextField].ToString(), dr[ValueField].ToString()));
            }
        }

        /// <summary>
        /// 直接通过字符数组获取下拉框列的item
        /// </summary>
        /// <param name="ColumnName">下拉框列列名</param>
        /// <param name="TextArray">显示的字符数组</param>
        /// <param name="ValueArray">值得字符数组</param>
        protected void SQueryPolutateComboBoxColumn(string ColumnName, string[] TextArray, string[] ValueArray)
        {
            GridViewDataComboBoxColumn gvdcb = gridView.Columns[ColumnName] as GridViewDataComboBoxColumn;
            for (int i = 0; i < TextArray.Length; i++)
            {
                gvdcb.PropertiesComboBox.Items.Add(new DevExpress.Web.ASPxEditors.ListEditItem(TextArray[i], ValueArray[i]));
            }
        }

        /// <summary>
        /// 判定strAry是否包含str
        /// </summary>
        /// <param name="str"></param>
        /// <param name="strAry"></param>
        /// <returns></returns>
        bool IsStringINArray(string str, string[] strAry)
        {
            for (int i = 0; i < strAry.Length; i++)
            {
                if (str == strAry[i])
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 导出功能
        /// </summary>
        /// <param name="saveAs">是否直接打开或保存（true为保存，false为打开）</param>
        /// <param name="page">调用exporter的页面</param>
        /// <param name="agvExporter">exporter</param>
        /// <param name="sType">导出类型</param>
        /// <param name="sFileName">文件名</param>
        protected void SQueryGridViewExport(bool saveAs, ASPxGridViewExporter agvExporter, string sType, string sFileName)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                //ASPxGridViewExporter1.OptionsPrint.PrintHeadersOnEveryPage = false;
                //ASPxGridViewExporter1.OptionsPrint.PrintFilterHeaders = true ? DefaultBoolean.True : DefaultBoolean.False;
                //ASPxGridViewExporter1.OptionsPrint.PrintColumnHeaders = true ? DefaultBoolean.True : DefaultBoolean.False;
                //ASPxGridViewExporter1.OptionsPrint.PrintRowHeaders = true ? DefaultBoolean.True : DefaultBoolean.False;
                //ASPxGridViewExporter1.OptionsPrint.PrintDataHeaders = true ? DefaultBoolean.True : DefaultBoolean.False;

                string contentType = "", fileName = "";

                switch (sType)
                {
                    case "application/ms-excel":
                        contentType = sType;
                        fileName = sFileName + ".xls";
                        agvExporter.WriteXls(stream);
                        break;
                    case "text/enriched":
                        contentType = sType;
                        fileName = sFileName + ".rtf";
                        agvExporter.WriteRtf(stream);
                        break;
                    case "application/pdf":
                        contentType = sType;
                        fileName = sFileName + ".pdf";
                        agvExporter.WritePdf(stream);
                        break;
                }

                byte[] buffer = stream.GetBuffer();

                string disposition = saveAs ? "attachment" : "inline";
                Response.Clear();
                Response.Buffer = false;
                Response.AppendHeader("Content-Type", contentType);
                Response.AppendHeader("Content-Transfer-Encoding", "binary");
                Response.AppendHeader("Content-Disposition", disposition + "; filename=" + fileName);
                Response.BinaryWrite(buffer);
                Response.End();
            }
        }

        /// <summary>
        /// 重新按新获取到的SQuerySQLString绑定GridView
        /// </summary>
        protected void SQueryGridViewReQuery()
        {
            SQueryDateSet.Retrieve();
            //SQueryTrimGridColumns(SQueryGridView, dt);
            if (!string.IsNullOrEmpty(SQueryTableName))
            {
                SQueryGridView.DataSource = SQueryDateSet.Tables[SQueryTableName];
            }
            else
            {
                SQueryGridView.DataSource = SQueryDateSet.Tables[0];
            }
            SQueryGridView.DataBind();
        }
        /// <summary>
        /// 直接通过字符数组获取下拉框的item
        /// </summary>
        /// <param name="combobox">下拉框</param>
        /// <param name="TextArray">显示的字符数组</param>
        /// <param name="ValueArray">值得字符数组</param>
        protected void SQueryPolutateComboBox( ASPxComboBox combobox,string[] TextArray, string[] ValueArray)
        {
            for (int i = 0; i < TextArray.Length; i++)
            {
                combobox.Items.Add(new DevExpress.Web.ASPxEditors.ListEditItem(TextArray[i], ValueArray[i]));
            }
        }
        /// <summary>
        /// 按sqlstr获取下拉框的item
        /// </summary>
        /// <param name="combobox">下拉框</param>
        /// <param name="strsql">获取item的sql</param>
        /// <param name="TextField">下拉框的text列映射值</param>
        /// <param name="ValueField">下拉框的value列映射值</param>
        protected void SQueryPolutateComboBox(ASPxComboBox combobox, string strsql, string TextField, string ValueField)
        {
            DataTable dt = new DataTable();
            dt = GlobalSqlHelper.ExecuteSQLToDataTable(strsql);
            foreach (DataRow dr in dt.Rows)
            {
                combobox.Items.Add(new DevExpress.Web.ASPxEditors.ListEditItem(dr[TextField].ToString(), dr[ValueField].ToString()));
            }
        }
        #endregion
    }
}
